import React, {Component} from 'react'
import { CancelButton } from "../Button"
import Sort from "./Sort"
import { sortBy } from 'lodash'
import './table.css'

/*
* 列明排序函数集合
* */
const SORTS = {
  NONE: list => list,
  TITLE: list => sortBy(list, 'title'),
  AUTHOR: list => sortBy(list, 'author'),
  COMMENTS: list => sortBy(list, 'comments').reverse(),
  POINTS: list => sortBy(list, 'points').reverse()
}
class Table extends Component {

  constructor(props) {
    super(props)
    this.state = {
      sortKey: 'NONE', // 当前需要排序列
      isReverse: false // 是否需要反转
    }

    this.onSort = this.onSort.bind(this)
  }

  onSort(sortKey) {
    console.log('sortKey', sortKey)
    console.log('this.state.sortKey', this.state.sortKey)
    const isReverse = this.state.sortKey === sortKey && !this.state.isReverse
    this.setState({
      sortKey,
      isReverse
    })
  }


  render() {
    const { tableRows, onMiss } = this.props
    const { sortKey, isReverse } = this.state
    const newTableRows = SORTS[sortKey](tableRows) // 根据sortKey,获取对应方法,对表格数据进行排序
    const sortTableRows = isReverse ? newTableRows.reverse() : newTableRows

    return (
      <div className='table'>
        <div className="table-header">
          <span>
              <Sort sortKey={'TITLE'} activeSortKey={sortKey} onSort={this.onSort}>Title</Sort>
          </span>
          <span>
             <Sort sortKey={'AUTHOR'} activeSortKey={sortKey} onSort={this.onSort}>Author</Sort>
          </span>
          <span>
             <Sort sortKey={'COMMENTS'} activeSortKey={sortKey} onSort={this.onSort}>Comments</Sort>
          </span>
          <span>
             <Sort sortKey={'POINTS'} activeSortKey={sortKey} onSort={this.onSort}>Points</Sort>
          </span>
          <span>
              Archive
          </span>
        </div>
        {sortTableRows && sortTableRows.map(item => (
          <div key={item.id} className="table-row">
            <span>{item.title}</span>
            <span>{item.author}</span>
            <span>{item.comments}</span>
            <span>{item.points}</span>
            <span>
              <CancelButton onClick={() => onMiss(item.id)}>miss</CancelButton>
            </span>
          </div>
        ))}
      </div>
    )
  }
}

export default Table
